package org.lemon.transport.coap.server.service;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.californium.elements.util.CertPathUtil;
import org.eclipse.californium.scandium.dtls.*;
import org.eclipse.californium.scandium.dtls.x509.NewAdvancedCertificateVerifier;
import org.eclipse.californium.scandium.util.ServerNames;
import org.lemon.transport.coap.server.session.CoapDtlsSessionInMemoryStorage;
import org.lemon.transport.context.auth.ValidateDeviceCredentialsResponse;
import org.lemon.transport.coap.server.session.CoapDtlsSessionInfo;
import org.lemon.transport.context.data.device.DeviceProfile;
import org.lemon.transport.context.data.device.DeviceTransportType;
import org.lemon.transport.context.service.TransportAuthServiceCallback;
import org.lemon.transport.context.service.TransportService;
import org.lemon.transport.context.utils.EncryptionUtil;
import org.lemon.transport.context.utils.SslUtil;
import org.lemon.transport.context.utils.StringUtils;

import javax.security.auth.x500.X500Principal;
import java.net.InetSocketAddress;
import java.security.cert.*;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Data
@Slf4j
public class CoapDtlsCertificateVerifier implements NewAdvancedCertificateVerifier {

    private TransportService transportService;
    private CoapDtlsSessionInMemoryStorage coapDtlsSessionInMemoryStorage;
    private long dtlsSessionInactivityTimeout;
    private long dtlsSessionReportTimeout;
    private boolean skipValidityCheckForClientCert;

    public CoapDtlsCertificateVerifier(TransportService transportService, long dtlsSessionInactivityTimeout, long dtlsSessionReportTimeout, boolean skipValidityCheckForClientCert) {
        this.transportService = transportService;
        this.dtlsSessionInactivityTimeout = dtlsSessionInactivityTimeout;
        this.dtlsSessionReportTimeout = dtlsSessionReportTimeout;
        this.skipValidityCheckForClientCert = skipValidityCheckForClientCert;
    }

    @Override
    public List<CertificateType> getSupportedCertificateTypes() {
        return Collections.singletonList(CertificateType.X_509);
    }

    @Override
    public CertificateVerificationResult verifyCertificate(ConnectionId cid, ServerNames serverName, InetSocketAddress remotePeer, boolean clientUsage, boolean verifySubject, boolean truncateCertificatePath, CertificateMessage message) {
        try {
            CertPath certPath = message.getCertificateChain();
            X509Certificate[] chain = certPath.getCertificates().toArray(new X509Certificate[0]);
            for (X509Certificate cert : chain) {
                try {
                    String strCert = SslUtil.getCertificateString(cert);
                    String sha3Hash = EncryptionUtil.getSha3Hash(strCert);
                    final ValidateDeviceCredentialsResponse[] deviceCredentialsResponse = new ValidateDeviceCredentialsResponse[1];
                    CountDownLatch latch = new CountDownLatch(1);
                    transportService.deviceX509CertValidate(DeviceTransportType.COAP, sha3Hash, new TransportAuthServiceCallback<ValidateDeviceCredentialsResponse>() {
                        @Override
                        public void onSuccess(ValidateDeviceCredentialsResponse msg) {
                            if (!StringUtils.isNullOrEmpty(msg.getCredentials())) {
                                deviceCredentialsResponse[0] = msg;
                            }
                            latch.countDown();
                        }

                        @Override
                        public void onError(Throwable e) {
                            log.error(e.getMessage(), e);
                            latch.countDown();
                        }
                    });
                    latch.await(10, TimeUnit.SECONDS);
                    ValidateDeviceCredentialsResponse msg = deviceCredentialsResponse[0];
                    if (msg != null && strCert.equals(msg.getCredentials())) {
                        DeviceProfile deviceProfile = msg.getDeviceProfile();
                        if (msg.hasDeviceInfo() && deviceProfile != null) {
                            coapDtlsSessionInMemoryStorage.put(remotePeer, new CoapDtlsSessionInfo(msg, deviceProfile));
                        }
                        break;
                    }
                } catch (InterruptedException |
                        CertificateEncodingException e) {
                    log.error(e.getMessage(), e);
                    AlertMessage alert = new AlertMessage(AlertMessage.AlertLevel.FATAL, AlertMessage.AlertDescription.BAD_CERTIFICATE);
                    throw new HandshakeException("Certificate chain could not be validated", alert);
                }
            }
            return new CertificateVerificationResult(cid, certPath, null);
        } catch (HandshakeException e) {
            log.trace("Certificate validation failed!", e);
            return new CertificateVerificationResult(cid, e, null);
        }
    }

    public ConcurrentMap<InetSocketAddress, CoapDtlsSessionInfo> getCoapDtlsSessionsMap() {
        return coapDtlsSessionInMemoryStorage.getDtlsSessionsMap();
    }

    @Override
    public List<X500Principal> getAcceptedIssuers() {
        return CertPathUtil.toSubjects(null);
    }

    @Override
    public void setResultHandler(HandshakeResultHandler resultHandler) {

    }
}
